import { defineStore } from 'pinia';
import axios from 'axios';
import router from '../router/index'; // 引入路由实例

export const useAuthStore = defineStore('auth', {
  state: () => ({
    user: JSON.parse(localStorage.getItem('user')) || null,
    token: localStorage.getItem('token') || null
  }),
  persist: true, // 启用持久化
  actions: {
    async login(credentials) {
      try {
        console.log(credentials);
        const response = await axios.post('/api/auth/login', credentials, {
          headers: {
            'Content-Type': 'application/json'
          }
        });
        console.log('Response from login:', response.data); // 打印后端返回的数据
        if (response.data && response.data.token) {
          this.token = response.data.token;
          localStorage.setItem('token', this.token);
          await this.fetchUser();
          router.push('/home'); // 使用引入的路由实例
        } else {
          throw new Error('登录失败，未获取到有效的 Token');
        }
      } catch (error) {
        console.error('登录失败:', error);
        if (error.response) {
          console.error('后端返回的错误:', error.response.data);
        }
        throw new Error('登录失败，请检查凭证');
      }
    },
    async register(userData) {
      try {
        await axios.post('/api/users', userData);
        router.push('/login'); // 使用引入的路由实例
      } catch (error) {
        throw new Error('注册失败，用户可能已存在');
      }
    },
    async fetchUser() {
      if (this.token) {
        const response = await axios.get('/api/auth/me', {
          headers: { Authorization: `Bearer ${this.token}` }
        });
        this.user = response.data;
        localStorage.setItem('user', JSON.stringify(response.data));
      }
    },
    logout() {
      this.user = null;
      this.token = null;
      localStorage.removeItem('token');
      localStorage.removeItem('user');
      router.push('/login'); // 使用引入的路由实例
    }
  }
});